<?php
namespace Secret\Controllers;

use Secret\Common\Utils;
use Silex\Application;
use Silex\ControllerProviderInterface;
use Silex\ControllerCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class PageCSP implements ControllerProviderInterface {

	public function connect(Application $app) {
		$content = array();
		$controllers = $app['controllers_factory'];
		$controllers->match('/sort/', array($this,'sort'), 'POST')->bind('sort-pages');
		$controllers->match('/', array($this,'pages'), 'GET')->bind('pages');
		$controllers->match('/remove/', array($this,'remove'), 'GET')->bind('remove-page');
		return $controllers;
	}

	public function pages(Application $app, Request $request) {
		$repo = $app['em']->getRepository('Secret\Entities\Content');
		$result = $repo->data('Page', '', array(), array('sort' => 'rank', 'order' => 'ASC'));
		$tree = Utils::buildTree(array('id' => 0), $result['_data']);
		return $app['twig']->render("pages.twig", array('tree' => $tree, 'returnURL' => Utils::getURL()));
	}
	
	public function remove(Application $app, Request $request) {
		$modelName = $request->get('modelName');
		$repo = $app['em']->getRepository('Secret\Entities\Content');
		$model = $repo->model(urldecode($modelName));
		$user = $app['user']->getUser();
		if ((!$user || $user->admin == 0) && $model['permission'] == 1) {
			return $app->abort(401);
		}
		
		$id = $request->request->get('id');
		$repo = $app['em']->getRepository('Secret\Entities\Content');
		$result = $repo->data('Page', '', array(), array('sort' => 'rank', 'order' => 'ASC'));
		$tree = Utils::buildTree(array('id' => 0), $result['_data']);
		$ids = Utils::withChildIds($tree, $id);
		foreach ($ids as $itm) {
			$entity = $repo->find($itm);
			$app['em']->remove($entity);
		}
		$app['em']->flush();
		return new Response('Success');
	}

	public function sort(Application $app, Request $request) {
		$data = json_decode($request->get('data'));
		$repo = $app['em']->getRepository('Secret\Entities\Content');
		$model = $repo->model('Page');
		$model['_data'] = array();
		foreach ($data as $itm) {
			$itm = (array) $itm;
			$model['_data'][] = array(
				'id' => $itm['id'],
				'rank' => $itm['rank'],
				'parentId' => $itm['parentId']
			);
		}
		$repo->save($model);
		return new Response('Success');
	}
}